package com.lagou.edu.spring.web;

import com.lagou.edu.spring.core.ApplicationContext;
import com.lagou.edu.spring.core.BeanDefinition;
import com.lagou.edu.spring.core.BeanDefinitionRegistry;
import com.lagou.edu.spring.core.BeanFactoryPostProcessor;
import com.lagou.edu.spring.exceptions.MySpringException;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.List;

/**
 * MySpringWebServlet注解处理逻辑
 *
 * @author 大犬
 * @date 2020/4/2
 */
public class MySpringWebServletProcessor implements BeanFactoryPostProcessor {

    private static ServletContext servletContext;

    public static void setServletContext(ServletContext servletContext) {
        MySpringWebServletProcessor.servletContext = servletContext;
    }

    @Override
    public void preProcessBeanFactory(BeanDefinitionRegistry beanDefinitionRegistry, ApplicationContext applicationContext) {
        List<BeanDefinition> allBeanDefinitions = beanDefinitionRegistry.getAllBeanDefinitions();
        allBeanDefinitions.forEach(this::processServletBean);
    }

    @SuppressWarnings("unchecked")
    private void processServletBean(BeanDefinition beanDefinition) {
        Class beanType = beanDefinition.getBeanType();
        MySpringWebServlet webServlet = (MySpringWebServlet) beanType.getAnnotation(MySpringWebServlet.class);
        if (webServlet != null) {
            try {
                Servlet servlet = servletContext.createServlet(beanType);
                beanDefinition.setProvideBean(servlet);
            } catch (ServletException e) {
                throw new MySpringException("create servlet failed", e);
            }
        }

    }
}
